package com.scf.fruit.business.useraddress.bo;

import com.scf.fruit.business.useraddress.po.UserAddressReq;
import com.scf.fruit.enums.ExceptionCodeEnum;
import com.scf.fruit.useraddress.UserAddressDto;
import com.scf.fruit.useraddress.UserAddressService;
import com.scf.fruit.util.IDUtil;
import com.scf.fruit.util.ResponseVo;
import com.scf.fruit.util.SpringCglibBeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : 孙超飞
 * @title :
 * @description :
 * @copyright :
 * @date : 2018-05-18 16:06
 */
@Component
public class UserAddressBo {
    @Resource
    private UserAddressService userAddressService;

    public ResponseVo saveUserAddress(Long userId, UserAddressReq req){
        ResponseVo res=new ResponseVo();
        UserAddressDto convert = SpringCglibBeanUtils.convert(req, UserAddressDto.class);
        convert.setUserId(userId);
        //如果库中已经存在直接返回地址id
        List<UserAddressDto> userAddressDtos = userAddressService.queryUserAddress(convert);
        if(!CollectionUtils.isEmpty(userAddressDtos)){
            res.setCode(ExceptionCodeEnum.EX_ADDRESS_EXIST_ERROR.getValue());
            res.setMsg(ExceptionCodeEnum.EX_ADDRESS_EXIST_ERROR.getMsg());
            res.setData(userAddressDtos.get(0).getId().toString());
            return res;
        }
        convert.setId(IDUtil.getId());
        boolean b = userAddressService.saveAddress(convert);
        if(!b){
            return new ResponseVo(ExceptionCodeEnum.EX_ADDRESS_ERROR.getValue(),ExceptionCodeEnum.EX_ADDRESS_ERROR.getMsg());
        }
        res.setData(convert.getId());
        return res;
    }
}
